package com.itheima.d2_buffered_stream;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test1 {
    /*
统计文件中特定字符出现多少次
     */
    public static void main(String[] args) {
        String key="上海";
        try {
            method1(key);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

public static int  method1(String key) throws IOException {
       int count=0;
        //读 创建字符缓冲输入流 按行读
    BufferedReader br=
            new BufferedReader(new FileReader("cc.txt"));

    String readLine=null;
  while (( readLine = br.readLine())!=null){
      //判断字符串中是否包含关键字
     /* if (readLine.contains(key)){
          count++;
      }*/
      String regex=key;
      Pattern pattern=Pattern.compile(regex);
      Matcher matcher=pattern.matcher(readLine);
      while (matcher.find()){
          count++;
      }
  }
    //判断是否有key关键字

    br.close();
     return count;
}

public static void method2(int count,String key) throws IOException {
    BufferedWriter bw=new BufferedWriter(new FileWriter("cc.txt",true));

    bw.newLine();
    bw.write("关键字"+key+"出现的次数为"+count);
    bw.close();
}


}
